package org.spring.aicloud.controller.model;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.baidubce.qianfan.model.image.Text2ImageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.spring.aicloud.entity.Answer;
import org.spring.aicloud.entity.myenum.AiModelEnum;
import org.spring.aicloud.entity.myenum.AiTypeEnum;
import org.spring.aicloud.service.IAnswerService;
import org.spring.aicloud.util.AppVariable;
import org.spring.aicloud.util.MinioUtil;
import org.spring.aicloud.util.ResponseEntity;
import org.spring.aicloud.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 百度大模型（千帆大模型）操作
 */
@RequestMapping("/qianfan")
@RestController
@Tag(name = "千帆大模型")
public class QianfanController {

    @Value("${qianfan.api-key}")
    private String apiKey;
    @Value("${qianfan.secret-key}")
    private String apiSecret;
    @Resource
    private IAnswerService answerService;
    @Resource
    private MinioUtil minIoUtil;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 聊天
     */
    @RequestMapping("/chat")
    public ResponseEntity chat(String question) {
        if (!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("问题不能为空");
        }
        //在调用接口之前，先针对用户加锁
        //创建key
        String lockKey = AppVariable.getModelLockKey
                (SecurityUtil.getCurrentUser().getUid(),
                        AiModelEnum.QIANFAN.getValue(), AiTypeEnum.CHAT.getValue());
        String content = ""; //大模型返回的结果
        boolean save = false;//数据是否保存成功
        //创建分布式锁实例
        RLock lock = redissonClient.getLock(lockKey);
        //尝试获取分布式锁
        boolean isLock = false;
        try {
            isLock = lock.tryLock(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!isLock) {
            //获取分布式锁失败
            return ResponseEntity.fail("请勿频繁调用接口");
        }
        try {
            //按照千帆的SDK进行接口的调用
            ChatResponse response = new Qianfan(apiKey, apiSecret).chatCompletion()
                    .model("ERNIE-Speed-8K") // 使用model指定预置模型
                    // .endpoint("completions_pro") // 也可以使用endpoint指定任意模型 (二选一)
                    .addMessage("user", question) // 添加用户消息 (此方法可以调用多次，以实现多轮对话的消息传递)
                    // .temperature(0.7) // 自定义超参数
                    .execute(); // 发起请求
            content = response.getResult();
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(content);
            answer.setModel(AiModelEnum.QIANFAN.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            answer.setType(AiTypeEnum.CHAT.getValue());
            save = answerService.save(answer);
        } catch (Exception ignored) {
        } finally {
            //3.释放锁
            lock.unlock();
        }
        if (save) {
            return ResponseEntity.success(content);
        }
        return ResponseEntity.fail("操作失败，请重试！");
    }

    /**
     * 获取所有的聊天记录
     */
    @RequestMapping("/getchatlist")
    public ResponseEntity getChatList() {
        //首先获取到当前的登录用户和调用的大模型
        long uid = SecurityUtil.getCurrentUser().getUid();
        int type = AiTypeEnum.CHAT.getValue();
        int model = AiModelEnum.QIANFAN.getValue();
        //将当前的uid和type和model封装成一个key
        String cacheKey = AppVariable.getListCacheKey(uid,model,type);
        Object value = redisTemplate.opsForValue().get(cacheKey);
        if (value == null){
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("model", AiModelEnum.QIANFAN.getValue());
            queryWrapper.eq("type", AiTypeEnum.CHAT.getValue());
            queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid());
            queryWrapper.orderByDesc("aid");
            List<Answer> list = answerService.list(queryWrapper);
            //查询到结果之后存储到缓存当中
            redisTemplate.opsForValue().set(cacheKey,list,1,TimeUnit.DAYS );
            //存储完成之后，将查询结果返回
            return ResponseEntity.success(list);
        }
        return ResponseEntity.success(value);
    }


    /**
     * 绘画
     */
    @RequestMapping("/draw")
    public ResponseEntity draw(String question) {
        if (!StringUtils.hasLength(question)) {
            // 输入为空
            return ResponseEntity.fail("请先输入内容！");
        }
        //在调用接口之前，先针对用户加锁
        //创建key
        String lockKey = AppVariable.getModelLockKey
                (SecurityUtil.getCurrentUser().getUid(),
                        AiModelEnum.QIANFAN.getValue(), AiTypeEnum.DRAW.getValue());
        String url = ""; //大模型返回的结果
        boolean save = false;//数据是否保存成功
        //创建分布式锁实例
        RLock lock = redissonClient.getLock(lockKey);
        //尝试获取分布式锁
        boolean isLock = false;
        try {
            isLock = lock.tryLock(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!isLock) {
            //获取分布式锁失败
            return ResponseEntity.fail("请勿频繁调用接口");
        }
        try {
            Text2ImageResponse response = new Qianfan(apiKey, apiSecret)
                    .text2Image()
                    .prompt(question)
                    .execute();
            byte[] image = response.getData().get(0).getImage();
            String fileName = "qf-" + UUID.randomUUID().toString().replace("-", "");
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(image)) {
                url = minIoUtil.upload(fileName, inputStream, "image/png");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(url);
            answer.setModel(AiModelEnum.QIANFAN.getValue());
            answer.setType(AiTypeEnum.DRAW.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            save = answerService.save(answer);
        } catch (Exception ignored) {
        } finally {
            //3.释放锁
            lock.unlock();
        }
        if (save) {
            return ResponseEntity.success(url);
        }
        return ResponseEntity.fail("操作失败，请重试！");
    }

    /**
     * 获取所有的绘画记录
     */
    @RequestMapping("/getdrawlist")
    public ResponseEntity getDrawList() {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("model", AiModelEnum.QIANFAN.getValue());
        queryWrapper.eq("type", AiTypeEnum.DRAW.getValue());
        queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid());
        queryWrapper.orderByDesc("aid");
        return ResponseEntity.success(answerService.list(queryWrapper));
    }
}
